package com.presalept.manipulatedata;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import com.presalept.polodo.ProjectMemberDO;


public class DelProjectMemeber {
	
	//insert projectmembers
	
		public static int DeleteProjectMemeber(List<ProjectMemberDO> projetmember) throws SQLException{
			
			int DelResult = 0;
			Connection dbConn = null;
			PreparedStatement dbProjectMemberStmt = null;
			ResultSet dbRs = null;
			int[] delProjectMemberResult;
		
			String dbProjectMemberSql = "DELETE FROM relationofprojectanduser WHERE projectid =? AND userid = ?;";
			try{
				
				dbConn = DbManager.getConnection();		
				
				dbProjectMemberStmt = dbConn.prepareStatement(dbProjectMemberSql);
					
				//del users from relationofprojectanduser
				
				for(Iterator<ProjectMemberDO> i = projetmember.iterator(); i.hasNext();){
					
					ProjectMemberDO pmdo = i.next();
					
					//when OperateType == 0 delete the record
					
					if(pmdo.getOperateType() == 0){
						
						dbProjectMemberStmt.setInt(1, pmdo.getProjectId());
					
						dbProjectMemberStmt.setInt(2, pmdo.getUserId());
					
						dbProjectMemberStmt.addBatch();	
					}
				}
				
				
				delProjectMemberResult = dbProjectMemberStmt.executeBatch();

				boolean isDelRight = false;
				for(int i = 0; i < delProjectMemberResult.length; i++){
						
					//if some record has del error, then rollback
						
						if(delProjectMemberResult[i] == 0){
							dbConn.rollback();
							break;
						}
						
						isDelRight = true;
					}
				
				if(isDelRight){
						
					DelResult = 1;
					
				}
				
			}finally{
				if (dbRs != null) dbRs.close();
				if (dbConn != null) dbConn.close();			
			}
			
			return DelResult;
		}

}
